package com.maven.front.controller.frontLogin;

import com.maven.front.aop.MyLog;
import com.maven.front.bean.EduUser;
import com.maven.front.bean.Result;
import com.maven.front.service.frontLogin.LoginService;
import com.maven.front.util.MD5;
import com.maven.front.util.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("user")
public class LoginController {

    @Resource
    private LoginService loginService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户查询
     * @param id
     * @return
     */
    @GetMapping("get/{id}")
    public Result getById(@PathVariable("id") int id){
        return loginService.getById(id);
    }

    /**
     * 登录验证
     * @param email
     * @param password
     * @return
     */
    @MyLog(value = "前台登录")
    @PostMapping("login")
    public Result login(String email, String password){
        String sign = MD5.sign(password,email,"utf-8");
        log.info("*********加密:"+sign);
        Result result = loginService.check(email,sign);
        if(result.getCode()!=200){
            return result;
        }
        EduUser eduUser = (EduUser) result.getData();
        String token = UUIDUtils.createSecureUUID();
        if(token!=null){
            redisTemplate.opsForValue().set(token,eduUser);
            redisTemplate.expire(token,15, TimeUnit.MINUTES);

            return new Result(200,"登录成功",token);
        }
        return new Result(253,"token生成失败");
    }

    /**
     * 验证是否登录状态
     * @param token
     * @return
     */
//    @MyLog(value = "前台验证是否登录")
    @PostMapping("isLogin")
    public Result isLogin(@RequestHeader String token){
        log.info("*****"+redisTemplate.opsForValue().get(token));
        EduUser eduUser = (EduUser) redisTemplate.opsForValue().get(token);
        log.info("******进入验证"+eduUser);
        if(ObjectUtils.isEmpty(eduUser)){
            return new Result(229,"token错误");
        }
        redisTemplate.expire(token,15,TimeUnit.MINUTES);
        return new Result(200,"成功",eduUser);
    }

    @MyLog(value = "前台注册")
    @PostMapping("register")
    public Result register(EduUser eduUser){
        String sign = MD5.sign(eduUser.getPassword(),eduUser.getEmail(),"utf-8");
        eduUser.setPassword(sign);
        return loginService.save(eduUser);
    }
}
